﻿// FIV Fast Image viewer
// http://code.google.com/p/fiv/
// 
// Copyright 2013, Ken Rentz.
//
// This is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of
// the License, or (at your option) any later version.
//
// This software is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this software; if not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301 USA, or see the FSF site: http://www.fsf.org.
// 

using System;
using System.Collections.Generic;

namespace FIV
{
	class FileListManager
	{
		public int NumberOfFiles 
		{ 
			get { return _FileList.Count; } 
		}

		public int PictureIndex {get; set;}

		private readonly List<string> _FileList;
		private readonly List<int> _Indexes;
		private int _Position;
		private bool _Shuffled;

		public FileListManager()
		{
			_FileList = new List<string>();
			_Indexes = new List<int>();
			Init();
		}

		public void Init()
		{
			_FileList.Clear();
			_Indexes.Clear();

			_Position = -1;
			_Shuffled = false;
		}

		public void AddFile(string value)
		{
			_FileList.Add(value);
			_Indexes.Add(NumberOfFiles - 1);  // zero indexed
		}

		public void AddFiles(List<string> values)
		{
			foreach (string filename in values)
				AddFile(filename);
		}

		public void NewFiles(List<string> values)
		{
			Init();
			AddFiles(values);
		}

		public string GetNextFile()
		{
			SetFilePosition(true);
			PictureIndex = _Position;
			return _FileList[PictureIndex];
		}

		public string GetPreviousFile()
		{
			SetFilePosition(false);
			PictureIndex = _Position;
			return _FileList[PictureIndex];
		}

		public string GetNextRandomFile()
		{
			SetFilePosition(true);
			PictureIndex = _Indexes[_Position];
			return _FileList[PictureIndex];
		}

		private void SetFilePosition(bool foreward)
		{
			// initialize the sorted list for random display
			if (!_Shuffled)
				Shuffle();
			if (foreward)
			{
				if (_Position >= NumberOfFiles - 1)
					_Position = -1;

				_Position++;
			}
			else
			{
				_Position--;
				if (_Position < 0)
					_Position = NumberOfFiles - 1;
			}
		}


		// Fisher–Yates shuffle
		public void Shuffle()
		{
			Random rng = new Random();
			int n = _Indexes.Count;
			while (n > 1)
			{
				n--;
				int k = rng.Next(n + 1);
				int value = _Indexes[k];
				_Indexes[k] = _Indexes[n];
				_Indexes[n] = value;
			}
			_Shuffled = true;
		}
	}
}
